package utils

import (
	"encoding/json"
	"net/http"
)

type JSONResponse struct {
	Writer http.ResponseWriter
}

func (r *JSONResponse) Success(data interface{}) {
	r.send(http.StatusOK, true, "", data)
}

func (r *JSONResponse) Failed(message string) {
	r.send(http.StatusOK, false, message, nil)
}

func (r *JSONResponse) send(statusCode int, success bool, message string, data interface{}) {
	response := struct {
		Success bool        `json:"success"`
		Data    interface{} `json:"data,omitempty"`
		Message string      `json:"message,omitempty"`
	}{
		Success: success,
		Data:    data,
		Message: message,
	}

	bytes, err := json.Marshal(response)
	if err != nil {
		http.Error(r.Writer, err.Error(), http.StatusInternalServerError)
		return
	}

	r.Writer.Header().Set("Content-Type", "application/json")
	r.Writer.WriteHeader(statusCode)
	r.Writer.Write(bytes)
}

func HandleAPIResponse(w http.ResponseWriter, err error, data interface{}) {
	res := JSONResponse{Writer: w}
	if err != nil {
		res.Failed(err.Error())
	} else {
		res.Success(data)
	}
}
